import axios from 'axios';
import qs from 'qs';
import React from 'react';

class Post extends React.Component {
  state = {
    data: [],
    component: this.props.loading || ''
  };

  async componentDidMount() {
    const { url, data, children, delay, error } = this.props;

    try {
      const result = await axios.post(url, qs.stringify(data));
      // console.log(result);
      //{data: Array(0), status: 200, statusText: 'OK', headers: {…}, config: {…}, …}

      this.setState(
        {
          data: result.data
        },
        () => {
          setTimeout(() => {
            this.setState({
              component: children(this.state.data)
            });
          }, delay || 0);
        }
      );
    } catch (e) {
      this.setState({
        component: error || 'Error'
      });

      throw e;
    }
  }

  async componentDidUpdate(prevProps) {
    const { url, data, children, delay, error } = this.props;

    if (prevProps.data !== data) {
      try {
        const result = await axios.post(url, qs.stringify(data));
        // console.log(result);
        //{data: Array(0), status: 200, statusText: 'OK', headers: {…}, config: {…}, …}

        this.setState(
          {
            data: result.data
          },
          () => {
            setTimeout(() => {
              this.setState({
                component: children(this.state.data)
              });
            }, delay || 0);
          }
        );
      } catch (e) {
        this.setState({
          component: error || 'Error'
        });

        throw e;
      }
    }
  }

  render() {
    return this.state.component;
  }
}

export default Post;
